package com.pencilisland.pay.app.mp.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.pencilisland.pay.api.bean.mp.app.MessageRequest;
import com.pencilisland.pay.api.bean.mp.app.MessageResponse;
import com.pencilisland.pay.api.bean.mp.app.WxLoginREQ;
import com.pencilisland.pay.api.bean.mp.app.WxLoginRES;
import com.pencilisland.pay.api.bean.wxpay.WxLoginResp;
import com.pencilisland.pay.api.service.CacheService;
import com.pencilisland.pay.api.service.WxpayService;
import com.pencilisland.pay.app.mp.service.MBService;
/**
* 报文逻辑处理.微信用户登录
*
* @author breeze
*/
@Service("MB_wxLogin")
public class  WxLoginMB implements MBService {

	@Autowired
	ObjectMapper objectMapper;
	@Autowired
	WxpayService wxpayService;
	@Autowired
	CacheService cacheService;

	@Override
	public MessageResponse process(MessageRequest request) {
		WxLoginREQ requestBean = getRequestBody(request);
		
		WxLoginRES res= new WxLoginRES(true,null,"OK");
		
		try {
			WxLoginResp result = wxpayService.login(requestBean.getCode());
			if(StringUtils.isEmpty(result.getOpenId())){
				return new WxLoginRES(false,null,"请求微信返回："+result.getErrmsg());
			}
			
			String sessionId = UUID.randomUUID().toString();
			cacheService.set(sessionId, result, 2*60*60L);
			
			res.setSessionId(sessionId);
			
		} catch (Exception e) {
			e.printStackTrace();
			return new WxLoginRES(false,null,"请求微信服务异常："+e.getMessage());
		}
		return res;
	}
	
	public WxLoginREQ getRequestBody(MessageRequest request){
		return objectMapper.convertValue(request.getBody(), WxLoginREQ.class);
	}

}
